<template>
	<view class="tab-page">
		<view class="nav-bar" v-if="showSearch">
			<view class="nav-search">
				<uni-search-bar :focus="true" radius="100" v-model="searchText" cancelButton="none" placeholder="搜索"></uni-search-bar>
			</view>
		</view>
		<scroll-view class="scroll-bar" v-else scroll-with-animation="true" scroll-y="true">
			<view class="moments-section" style="margin-right: 20rpx">
				<view class="moment-item release" @click="goFb">
					<view class="avatar-wrapper">
						<image src="/static/avatar.jpg" mode="aspectFill" class="avatar"></image>
						<view class="add-icon">+</view>
					</view>
					<view class="moment-name">发布时刻</view>
				</view>
				<scroll-view class="moments-list" scroll-x>
					<view class="moment-item" v-for="(item, index) in friendsList" :key="index" @click="onSendMessage(item)">
						<view class="avatar-wrapper">
							<head-image :url="item.headImage" :name="item.nickName"></head-image>
							<view v-if="item.statusDot" :class="['status-dot', item.statusDot]"></view>
						</view>
						<view class="moment-name">{{ item.nickName }}</view>
					</view>
				</scroll-view>
			</view>

			<view class="meeageList" style="margin-top: 20rpx">
				<view class="meeageListItem" v-for="(item, index) in messageList" :key="index" @click="goPage(item)">
					<view class="" style="display: flex">
						<view class="imageBox">
							<image :src="item.Image" mode="aspectFit"></image>
						</view>
						<view class="">
							<view class="meeageTitle"> {{ item.title }} </view>
							<view class="meeageText"> {{ item.text }} </view>
						</view>
					</view>
					<view class="meeageTime"> {{ item.time }} </view>
				</view>
			</view>
			<view v-for="(chat, index) in chatList" :key="index + '-' + chat.lastSendTime">
				<long-press-menu v-if="isShowChat(chat)" :items="menu.items" @select="onSelectMenu($event, index)">
					<chat-item :chat="chat" :index="index" :active="menu.chatIdx == index"></chat-item>
				</long-press-menu>
			</view>
		</scroll-view>
		<popup-modal ref="modal"></popup-modal>
	</view>
</template>

<script>
	import * as wsApi from '@/common/wssocket';
	export default {
		data() {
			return {
				showSearch: false,
				accessToken: uni.getStorageSync("loginInfo").accessToken,
				userId: uni.getStorageSync("userId"),
				searchText: "",
				friendsList: [],
				chatType: [],
        messageList: [
          {
            Image: "/static/image/gz.png",
            title: "最新关注",
            text: "点击进入关注列表",
            time: "",
          },
          {
            Image: "/static/image/like_and_favorite.png",
            title: "点赞与收藏",
            text: "点击进入点赞与收藏列表",
            time: "",
          },
          {
            Image: "/static/image/img.png",
            title: "评论和@",
            text: "点击进入评论和@列表",
            time: "",
          },
				],
				menu: {
					show: false,
					style: "",
					chatIdx: -1,
					isTouchMove: false,
					items: [
						{ key: "DELETE", name: "删除该聊天", icon: "trash", color: "#e64e4e" },
						{ key: "TOP", name: "置顶该聊天", icon: "arrow-up" }
					],
				},
			};
		},
		onLoad(options) {
			uni.setStorageSync("loginInfo", options);
			uni.setStorageSync("userId", options.userId);

			getApp().$vm.init();

			if (options.reconnectSocket === 'true' && !wsApi.isConnected()) {
				// console.log("检测到需要重连WebSocket");
				// 重新连接WebSocket
				getApp().$vm.reconnectWs();
			}

			// 监听WebSocket重连事件
			uni.$on('WS_RECONNECTED', this.handleWebSocketReconnect);

			// 监听新消息事件
			uni.$on('NEW_MESSAGE_RECEIVED', this.refreshChatList);
		},
		onShow() {
			// console.log('this.friendStore.friends', this.friendStore.friends);
			this.getFriendsList()

			// 主动检查消息更新
			if (!this.chatStore.isLoading()) {
				// 静默拉取离线消息
				this.chatStore.fetchChats(true).then((res) => {

					console.log("聊天页面刷新消息完成");
				}).catch(err => {
					console.error("拉取消息失败:", err);
				});
			}
			// 每次显示页面时，主动刷新聊天列表
			this.refreshChatList();
		},
		methods: {
			getFriendsList() {
				this.$http({
					url: "/friend/findFriendsForBlog",
					data: { blogUserId: uni.getStorageSync("userId") },
					method: "POST",
				}).then((user) => {
					this.friendsList = user;
				});
			},
			goFb() {
				switch (uni.getSystemInfoSync().platform) {
					case "android":
						window.AndroidBridge.notePublishEvent();
						console.log("运行Android上");
						break;
					case "ios":
						window.webkit.messageHandlers.notePublishEvent.postMessage();
						break;
					default:
						console.log("运行在开发者工具上");
						break;
				}
			},
			fn(data) {
				switch (uni.getSystemInfoSync().platform) {
					case "android":
						let ddd = data;
						let d = JSON.stringify(ddd);
						console.log(d, "都是对的");
						window.AndroidBridge.pushNewWebVC(d);
						console.log("运行Android上");
						break;
					case "ios":
						window.webkit.messageHandlers.pushNewWebVC.postMessage(data);
						break;
					default:
						console.log("运行在开发者工具上");
						break;
				}
			},
      goPage(item) {
        if (item.title == "点赞与收藏") {
          switch (uni.getSystemInfoSync().platform) {
            case "android":
              let ddd = {
                hideNavBar: "1",
                hideTotalNavBar: "1",
                hideBottomSafeBar: "1",
                navtitle: "点赞与收藏",
                url: `https://www.yaozhuasocial.com/yaozhua/yaozhua_shequ/#/pages/users/users1?type=0&authorId=${uni.getStorageSync("userId")}`,
              };
              let d = JSON.stringify(ddd);
              console.log(d, "都是对的");
              window.AndroidBridge.pushNewWebVC(d);
              console.log("运行Android上");
              break;
            case "ios":
              window.webkit.messageHandlers.pushNewWebVC.postMessage({
                hideNavBar: "1",
                hideTotalNavBar: "0",
                hideBottomSafeBar: "0",
                navtitle: "点赞与收藏",
                url: `https://www.yaozhuasocial.com/yaozhua/yaozhua_shequ/#/pages/users/users1?type=0&authorId=${uni.getStorageSync("userId")}`,
              });
              break;
            default:
              console.log("运行在开发者工具上");
              break;
          }
        } else if (item.title == "最新关注") {
          switch (uni.getSystemInfoSync().platform) {
            case "android":
              let ddd = {
                hideNavBar: "1",
                hideTotalNavBar: "0",
                hideBottomSafeBar: "0",
                navtitle: "最新关注",
                url: `https://www.yaozhuasocial.com/yaozhua/yaozhua_shequ/#/pages/users/users?type=1&authorId=${uni.getStorageSync("userId")}`,
              };
              let d = JSON.stringify(ddd);
              console.log(d, "都是对的");
              window.AndroidBridge.pushNewWebVC(d);
              console.log("运行Android上");
              break;
            case "ios":
              window.webkit.messageHandlers.pushNewWebVC.postMessage({
                hideNavBar: "1",
                hideTotalNavBar: "1",
                hideBottomSafeBar: "1",
                navtitle: "最新关注",
                url: `https://www.yaozhuasocial.com/yaozhua/yaozhua_shequ/#/pages/users/users?type=1&authorId=${uni.getStorageSync("userId")}`,
              });
              break;
            default:
              console.log("运行在开发者工具上");
              break;
          }
        } else if (item.title == "评论和@") {
          switch (uni.getSystemInfoSync().platform) {
            case "android":
              let ddd = {
                hideNavBar: "0",
                hideTotalNavBar: "0",
                hideBottomSafeBar: "0",
                navtitle: "评论和@",
                url: `https://www.yaozhuasocial.com/yaozhua/yaozhua_shequ/#/pages/replays/replays`,
              };
              let d = JSON.stringify(ddd);
              console.log(d, "都是对的");
              window.AndroidBridge.pushNewWebVC(d);
              console.log("运行Android上");
              break;
            case "ios":
              window.webkit.messageHandlers.pushNewWebVC.postMessage({
                hideNavBar: "0",
                hideTotalNavBar: "0",
                hideBottomSafeBar: "0",
                navtitle: "评论和@",
                url: `https://www.yaozhuasocial.com/yaozhua/yaozhua_shequ/#/pages/replays/replays`,
              });
              break;
            default:
              console.log("运行在开发者工具上");
              break;
          }
        }
      },
			onSelectMenu(item, chatIdx) {
				switch (item.key) {
					case "DELETE":
						this.removeChat(chatIdx);
						break;
					case "TOP":
						this.moveToTop(chatIdx);
						break;
					default:
						break;
				}
				this.menu.show = false;
			},
			removeChat(chatIdx) {
				this.chatStore.removeChat(chatIdx);
			},
			moveToTop(chatIdx) {
				this.chatStore.moveTop(chatIdx);
			},
			isShowChat(chat) {
				if (chat.delete) {
					return false;
				}
				return !this.searchText || chat.showName.includes(this.searchText);
			},
			onSearch() {
				this.showSearch = !this.showSearch;
				this.searchText = "";
			},
			friends() {
				return this.friendStore.friends;
			},
			onSendMessage(item) {
				// 从头部点进去
				this.$http({
					url: "/user/find/" + item.id,
					method: "GET",
				}).then((user) => {
					console.log(user);
					this.userInfo = user;
					let chat = {
						type: "PRIVATE",
						targetId: this.userInfo.id,
						showName: this.userInfo.nickName,
						headImage: this.userInfo.headImage,
					};
					this.chatStore.openChat(chat);
					console.log(`https://www.yaozhuasocial.com/yaozhua/yaozhua_w/#/pages/chat/chat-box?targetId=${this.userInfo.id}&accessToken=${this.accessToken}&userId=${this.userId}`);
					let data = {
						hideNavBar: "0",
						hideTotalNavBar: "1",
						hideBottomSafeBar: "1",
						url: `https://www.yaozhuasocial.com/yaozhua/yaozhua_w/#/pages/chat/chat-box?targetId=${this.userInfo.id}&accessToken=${this.accessToken}&userId=${this.userId}`,
					};
					this.fn(data);
					window.webkit.messageHandlers.pushNewWebVC.postMessage({
						hideNavBar: "1",
						hideTotalNavBar: "0",
						hideBottomSafeBar: "0",
						url: `https://www.yaozhuasocial.com/yaozhua/yaozhua_w/#/pages/chat/chat-box?targetId=${this.userInfo.id}&accessToken=${this.accessToken}&userId=${this.userId}`,
					});
				});
			},
			// 处理WebSocket重连事件
			handleWebSocketReconnect() {
				console.log("聊天列表页面检测到WebSocket重连");
				// 刷新聊天列表
				this.refreshChatList();
			},

			// 刷新聊天列表
			refreshChatList() {
				// 强制更新视图
				if (this && this.$forceUpdate) this.$forceUpdate();

				// 更新角标
				if (this.$badge) {
					this.$badge.refreshFriendBadge && this.$badge.refreshFriendBadge();
					this.$badge.refreshChatBadge && this.$badge.refreshChatBadge();
				}
			},
		},
		computed: {
			chatList() {
				return [...this.chatStore.chats];
			},
			unreadCount() {
				let count = 0;
				this.chatStore.chats.forEach((chat) => {
					if (!chat.delete) {
						count += chat.unreadCount;
					}
				});
				return count;
			},
			loading() {
				return this.chatStore.isLoading();
			},
			initializing() {
				return !getApp().$vm.isInit;
			},
		},
		watch: {
			unreadCount(newCount, oldCount) {
				this.$badge.refreshChatBadge();
			},
		},
		onUnload() {
			// 移除事件监听
			uni.$off('WS_RECONNECTED', this.handleWebSocketReconnect);
			uni.$off('NEW_MESSAGE_RECEIVED', this.refreshChatList);
		},

	};
</script>

<style lang="scss">
	.tab-page {
		min-height: 100vh;

		.chat-tip {
			position: absolute;
			top: 400rpx;
			padding: 50rpx;
			text-align: left;
			line-height: 50rpx;
			font-size: 30rpx;
			color: $im-text-color-lighter;
		}

		.chat-loading {
			display: block;
			width: 100%;
			height: 120rpx;
			background: white;

			color: $im-text-color-lighter;

			.loading-box {
				position: relative;
			}
		}

		.scroll-bar {
			flex: 1;
			height: 100%;

			.moments-section {
				display: flex;
				align-items: center;
				padding: 20rpx 0;
				border-bottom: 1px solid #f0f0f0;

				.moments-list {
					display: flex;
					overflow-x: auto;
					-webkit-overflow-scrolling: touch;
					white-space: nowrap;
				}

				.moment-item {
					display: inline-block;
					flex-direction: column;
					align-items: center;
					margin-right: 40rpx;
					flex-shrink: 0;

					&:last-child {
						margin-right: 0;
					}

					.avatar-wrapper {
						position: relative;
						width: 100rpx;
						height: 100rpx;
						border-radius: 50%;
						background-color: #eee;

						.avatar {
							width: 100%;
							height: 100%;
							border-radius: 50%;
						}

						.plus-icon {
							position: absolute;
							bottom: 0;
							right: 0;
							transform: translate(25%, 25%);
							width: 40rpx;
							height: 40rpx;
							border-radius: 50%;
							background-color: #4cd964;
							border: 2rpx solid white;
							display: flex;
							justify-content: center;
							align-items: center;
							font-size: 24rpx;
							color: white;
						}

						.status-dot {
							position: absolute;
							top: 0;
							right: 0;
							transform: translate(25%, -25%);
							width: 20rpx;
							height: 20rpx;
							border-radius: 50%;
							border: 2rpx solid white;

							&.orange {
								background-color: #ff9800;
							}

							&.red {
								background-color: #f44336;
							}

							&.yellow {
								background-color: #ffeb3b;
							}
						}

						.add-icon {
							position: absolute;
							bottom: 0;
							right: 0;
							transform: translate(25%, -25%);
							width: 32rpx;
							height: 32rpx;
							background: #d9f700;
							border-radius: 50%;
							border: 2rpx solid white;
							color: #171717;
							font-size: 15px;
							display: flex;
							justify-content: center;
							align-items: center;
							line-height: 1.5;
						}
					}

					.moment-name {
						margin-top: 10rpx;
						font-size: 26rpx;
						color: #333;
						text-align: center;
						white-space: nowrap;
						overflow: hidden;
						text-overflow: ellipsis;
						max-width: 120rpx;
					}
				}

				.release {
					padding: 0 60rpx;
					margin-right: 0;
					font-weight: bold;
					font-size: 28rpx;
					color: #303030;
				}
			}

			.chatType {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 40rpx 0;

				.chatType-item {
					width: 33.3%;
					display: flex;
					flex-direction: column;
					align-items: center;
					font-size: 26rpx;
					color: #171717;

					image {
						width: 96rpx;
						margin-bottom: 10rpx;
					}
				}
			}

			.meeageList {
				width: 92vw;
				margin: 0 auto;

				.meeageListItem {
					width: 100%;
					height: 168rpx;
					display: flex;
					align-items: center;
					justify-content: space-between;
					background: #ffffff;
					border-radius: 16rpx;
					padding: 0 32rpx;
					margin-bottom: 16rpx;

					.imageBox {
						width: 104rpx;
						height: 104rpx;
						margin-right: 24rpx;

						image {
							width: 100%;
							height: 100%;
							border-radius: 50%;
						}
					}

					.meeageTitle {
						font-weight: 600;
						font-size: 32rpx;
						color: #44496a;
						margin-bottom: 8rpx;
					}

					.meeageText {
						font-weight: 400;
						font-size: 28rpx;
						color: #8e8e92;
					}

					.meeageTime {
						font-weight: 400;
						font-size: 24rpx;
						color: #8e8e92;
					}
				}
			}
		}
	}
</style>
